<template>
    <div class="comment-container">
        <!-- 查询表单 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="评论者" prop="userName">
                    <el-input v-model="searchForm.userName" placeholder="用户名" clearable />
                </el-form-item>
                <el-form-item label="评论内容" prop="content">
                    <el-input v-model="searchForm.content" placeholder="评论内容" clearable />
                </el-form-item>
                <el-form-item label="发布时间">
                    <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadData">查询</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 评论列表 -->
        <el-scrollbar class="scroll-container">
            <div class="list-container">
                <el-card v-for="comment in commentList" :key="comment.id" class="comment-card">
                    <!-- 用户信息 -->
                    <div class="user-info">
                        <el-image :src="getAvatarUrl(comment.user?.avatar)" class="avatar"
                            :preview-src-list="[getAvatarUrl(comment.user?.avatar)]">
                            <template #error>
                                <div class="avatar-error">
                                    <el-icon><User /></el-icon>
                                </div>
                            </template>
                        </el-image>
                        <div class="user-details">
                            <div class="nickname">{{ comment.user?.nickName || '未知用户' }}</div>
                            <div class="username">@{{ comment.user?.userName || comment.commenterId }}</div>
                            <div class="time">{{ formatTime(comment.timestamp) }}</div>
                        </div>
                    </div>

                    <!-- 父评论 -->
                    <div v-if="comment.parentId" class="parent-comment">
                        <el-button type="text" @click="toggleParentComment(comment)">
                            {{ comment.showParent ? '收起' : '展开' }}父评论
                        </el-button>
                        <div v-if="comment.showParent && comment.parentComment" class="parent-content">
                            <div class="parent-header">
                                <el-icon><CaretRight /></el-icon>
                                <span class="parent-user">{{ comment.parentComment.user?.nickName || '未知用户' }}：</span>
                            </div>
                            <div class="parent-text">{{ comment.parentComment.content }}</div>
                        </div>
                    </div>

                    <!-- 评论内容 -->
                    <div class="comment-content">{{ comment.content }}</div>

                    <!-- 帖子缩略图 -->
                    <div class="post-thumbnail" v-if="comment.post?.urls?.length > 0">
                        <router-link :to="`/post/${comment.postId}`">
                            <div class="media-wrapper">
                                <el-image 
                                    v-if="isImage(comment.post.urls[0])"
                                    :src="getMediaUrl(comment.post.urls[0])" 
                                    fit="cover"
                                    class="thumbnail-image"
                                    :preview-src-list="getPreviewList(comment.post.urls)"
                                >
                                    <template #error>
                                        <div class="thumbnail-error">
                                            <el-icon><Picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                                <div v-else class="video-thumbnail">
                                    <el-icon class="video-icon"><VideoPlay /></el-icon>
                                    <span class="video-text">视频</span>
                                </div>
                            </div>
                        </router-link>
                    </div>
                </el-card>
            </div>
        </el-scrollbar>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
                :total="pagination.total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" background
                @size-change="loadData" @current-change="loadData" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getCommentById, getComments } from '@/api/comment'
import { getUserById } from '@/api/user'
import { getPostById } from '@/api/post'
import { CaretRight, User, VideoPlay, Picture } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'

const router = useRouter()
const BASE_URL = 'http://localhost:8081'

// 响应式数据
const commentList = ref([])
const searchForm = reactive({
    userName: '',
    content: '',
    dateRange: []
})
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
})

// 工具方法
const getAvatarUrl = (url) => url ? `${BASE_URL}/avatars/${url}` : ''
const formatTime = (time) => dayjs(time).format('YYYY-MM-DD HH:mm')
const isImage = (url) => /\.(jpg|jpeg|png|gif)$/i.test(url)
const isVideo = (url) => /\.(mp4|webm|ogg)$/i.test(url)
const getMediaUrl = (filename) => `${BASE_URL}/media/${filename.replace(/^\//, '')}`
const getPreviewList = (urls) => urls.filter(url => isImage(url)).map(url => getMediaUrl(url))

// 加载父评论
const loadParentComment = async (comment) => {
    try {
        const res = await getCommentById(comment.parentId)
        if (res.data) {
            const parent = res.data
            // 加载父评论用户信息
            const userRes = await getUserById(parent.commenterId)
            comment.parentComment = {
                ...parent,
                user: userRes.data
            }
        }
    } catch (error) {
        ElMessage.error('父评论加载失败')
        comment.parentComment = null
    }
}

// 切换父评论显示
const toggleParentComment = async (comment) => {
    comment.showParent = !comment.showParent
    if (comment.showParent && !comment.parentComment) {
        await loadParentComment(comment)
    }
}

// 加载数据
const loadData = async () => {
    try {
        const params = {
            offset: (pagination.current - 1) * pagination.size,
            size: pagination.size,
            userName: searchForm.userName || undefined,
            content: searchForm.content || undefined,
            startTime: searchForm.dateRange?.[0] || undefined,
            endTime: searchForm.dateRange?.[1] || undefined
        }

        const res = await getComments(params)
        
        const commentsWithData = await Promise.all(
            res.data.map(async comment => {
                try {
                    // 并行加载用户和帖子信息
                    const [userRes, postRes] = await Promise.all([
                        getUserById(comment.commenterId),
                        getPostById(comment.postId)
                    ])
                    
                    return { 
                        ...comment, 
                        user: userRes.data,
                        post: postRes.data,
                        showParent: false,
                        parentComment: null
                    }
                } catch (error) {
                    console.error('加载数据失败:', error)
                    return { 
                        ...comment, 
                        user: null,
                        post: null,
                        showParent: false,
                        parentComment: null
                    }
                }
            })
        )

        commentList.value = commentsWithData
        pagination.total = res.total
    } catch (error) {
        ElMessage.error('评论加载失败')
        console.error('加载评论列表失败:', error)
    }
}

// 初始化加载
onMounted(() => {
    loadData()
})
</script>

<style scoped>
.comment-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.search-card {
    margin-bottom: 10px;
    flex-shrink: 0;
}

.scroll-container {
    flex: 1;
    overflow: hidden;
}

.list-container {
    padding: 10px;
}

.comment-card {
    margin-bottom: 15px;
    position: relative;
    min-height: 120px;
}

.user-info {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
}

.avatar-error {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    color: #999;
}

.user-details {
    flex: 1;
}

.nickname {
    font-weight: 500;
    font-size: 14px;
}

.username {
    color: #666;
    font-size: 12px;
}

.time {
    color: #999;
    font-size: 12px;
}

.parent-comment {
    margin: 10px 0;
    padding: 10px;
    background: #f8f8f8;
    border-radius: 4px;
}

.parent-header {
    display: flex;
    align-items: center;
    color: #666;
    margin-bottom: 5px;
}

.parent-user {
    font-size: 13px;
}

.parent-text {
    color: #333;
    font-size: 14px;
    line-height: 1.4;
}

.comment-content {
    font-size: 14px;
    line-height: 1.5;
    color: #333;
    margin-right: 120px;
}

.post-thumbnail {
    position: absolute;
    top: 15px;
    right: 15px;
    width: 100px;
    height: 100px;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.2s;
    border: 1px solid #ebeef5;
}

.media-wrapper {
    width: 100%;
    height: 100%;
    background: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
}

.thumbnail-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.video-thumbnail {
    color: #606266;
    text-align: center;
    padding: 10px;
}

.video-icon {
    font-size: 28px;
    margin-bottom: 5px;
}

.video-text {
    display: block;
    font-size: 12px;
}

.thumbnail-error {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
}

.post-thumbnail:hover {
    transform: scale(1.03);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pagination-container {
    padding: 20px;
    background: white;
    box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
    z-index: 1;
}
</style>